<template>
    <div class="event-main">
        <img
            src="~/assets/images/riskdetection/Artboard2.png"
            alt=""
            class="Artboard2"
        />
        <div class="risk-detection-title">税务<span>风险检测</span></div>
        <div class="risk-detection-tips">
            涉税财务核算风险
            <div></div>
            税务风险标记
            <div></div>
            财务状况分析
        </div>
        <div class="form">
            <!-- <el-input
                v-model="form.companyName"
                placeholder="请输入企业名称"
                class="risk-detection-input input1"
            ></el-input> -->
            <el-autocomplete
                v-model="form.companyName"
                value-key="companyName"
                :fetch-suggestions="querySearchAsync"
                class="risk-detection-input input1"
                placeholder="请输入企业名称"
                @select="handleSelect"
            ></el-autocomplete>
            <el-input
                v-model="form.taxpayerld"
                placeholder="纳税人识别号（无需输入）"
                class="risk-detection-input input2"
            ></el-input>
            <div class="sbsj-date-jia">
                <el-date-picker
                    v-model="value2"
                    type="month"
                    placeholder="请选择申报时间"
                    value-format="yyyy-MM"
                    :picker-options="pickerOptions"
                    class="sbsj-date"
                    @change="change"
                >
                </el-date-picker>
                <div class="date-text">
                    {{ jiaDate }}
                </div>
            </div>

            <div class="form-item">
                <span class="label">是否匿名生成报告</span>
                <el-radio-group v-model="form.isAnonymity" class="radio">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                </el-radio-group>
            </div>
            <div class="submit">
                <el-button
                    type="primary"
                    class="button"
                    @click="Sm2service_set_report"
                    >获取报告</el-button
                >
            </div>
            <div class="selects">
                <div class="select-item" @click="gpylbg">
                    样例报告
                    <span>></span>
                </div>
                <div class="select-item" @click="gomyreport">
                    我的报告
                    <span>></span>
                </div>
            </div>
            <div class="keyong-num">
                <div>
                    可用次数：{{ userInfo ? userInfo.chashuibao_num : 0 }}次
                </div>
                <div
                    class="zjcs"
                    @click="set_payVipShow({ show: true, index: 3 })"
                >
                    增加次数>
                </div>
            </div>

            <div class="tips">
                郑重承诺:本报告仅对用户本人可见，平台及他人无权查看。如信息在平台泄露，平台将全权承担法律责任。
            </div>
        </div>
    </div>
</template>

<script>
import {
    Sm2service_set_report,
    Sm2service_getbusinessfuzzy,
    Sm2service_get_data,
    Sm2service_check_report,
    getanalysedata2,
} from "@/assets/api/indexApi.js";
import { mapMutations, mapState, mapActions } from "vuex";

// 获取当前年月
const now = new Date();
let currentYear = now.getFullYear();
let currentMonth = now.getMonth();
if (currentMonth == 0) {
    currentMonth = 12;
    currentYear--;
}
let startcurrentYear = currentYear - 3;
let startcurrentMonth = currentMonth + 1;
if (startcurrentMonth == 13) {
    startcurrentMonth = 1;
    startcurrentYear++;
}

export default {
    name: "riskDetection",
    async asyncData({ route }) {
        let data = {
            mateInfo: {
                title: "风险检测",
                keywords: "",
                description: "",
            },
            relateddata: [],
            all_based_source: [],
            dataList: [],
        };

        return data;
    },
    components: {},
    layout: "home",
    head() {
        return {
            __dangerouslyDisableSanitizers: ["script"],
            title: this.mateInfo.title + "-【小竹财税平台】",
            meta: [
                {
                    hid: "description",
                    name: "description",
                    content: this.mateInfo.description,
                },
                {
                    hid: "keywords",
                    name: "keywords",
                    content: this.mateInfo.keywords,
                },
            ],
        };
    },
    data() {
        return {
            form: {
                companyName: "",
                taxpayerld: "",
                isAnonymity: "0",
            },
            value2: "",
            jiaDate: "",
            beginDate: "",
            overDate: "",
            pickerOptions: {
                disabledDate(time) {
                    return (
                        startcurrentYear > time.getFullYear() ||
                        (startcurrentYear == time.getFullYear() &&
                            startcurrentMonth > time.getMonth() + 1) ||
                        (currentYear == time.getFullYear() &&
                            currentMonth < time.getMonth() + 1)
                    );
                },
            },

            restaurants: [],
        };
    },
    computed: {
        ...mapState("common", {
            userInfo: (state) => state.userInfo,
        }),
    },
    created() {},
    beforeMount() {},
    beforeDestroy() {
        try {
            document.removeEventListener(
                "visibilitychange",
                this.handleVisibilityChange
            );
        } catch (error) {}
    },
    mounted() {
        document.addEventListener(
            "visibilitychange",
            this.handleVisibilityChange
        );
        getanalysedata2({
            m_id: 17,
            type: 1,
            describe: "风险检测",
            code: "PW1",
        });
    },
    watch: {},
    methods: {
        ...mapMutations("common", [
            "setmenuIndex",
            "setloginShow",
            "set_payVipShow",
        ]),
        ...mapActions("common", ["getUserInfo"]),

        handleVisibilityChange() {
            if (document.hidden) {
                console.log("用户离开了当前页面");
            } else {
                console.log("用户回到了当前页面");
                let FXJC_CSB_orderNo = localStorage.getItem("FXJC_CSB_orderNo");
                if (FXJC_CSB_orderNo)
                    this.Sm2service_check_report(FXJC_CSB_orderNo);
            }
        },

        async Sm2service_check_report(FXJC_CSB_orderNo) {
            localStorage.removeItem("FXJC_CSB_orderNo");
            this.getUserInfo();
            // const res = await Sm2service_check_report({
            //     orderNo: FXJC_CSB_orderNo,
            // });
            // if (res.code == 1) {
            //     this.getUserInfo();
            // }
        },

        change(inputYearMonth) {
            // 验证输入格式
            let inputParts = inputYearMonth.split("-");
            if (
                inputParts.length !== 2 ||
                isNaN(inputParts[0]) ||
                isNaN(inputParts[1]) ||
                inputParts[1].length !== 2
            ) {
                throw new Error("Invalid input format. Expected yyyy-mm.");
            }

            let startYear = parseInt(inputParts[0], 10);
            let startMonth = parseInt(inputParts[1], 10);

            // 获取当前年月
            // const now = new Date();
            // let currentYear = now.getFullYear();
            // let currentMonth = now.getMonth(); // 月份从0开始，所以要+1
            // if (currentMonth == 0) {
            //     currentMonth = 12;
            //     currentYear--;
            // }

            // 计算结束年月（先假设是开始年月加十一个月）
            let endYear = startYear;
            let endMonth = startMonth + 11;

            // 如果结束月份超过12，则调整到下一年的月份
            if (endMonth > 12) {
                endMonth -= 12;
                endYear += 1;
            }

            // 如果结束年月超过了当前年月，则调整开始年月
            if (
                endYear > currentYear ||
                (endYear === currentYear && endMonth > currentMonth)
            ) {
                // 计算需要回退多少个月才能确保在当前年月内
                let monthsToSubtract = 0;
                if (endYear > currentYear) {
                    monthsToSubtract =
                        (endYear - currentYear) * 12 + endMonth - currentMonth;
                } else {
                    monthsToSubtract = endMonth - currentMonth;
                }

                // 至少要保证有十二个月的时间范围
                monthsToSubtract = Math.min(monthsToSubtract, 11); // 因为至少保留一个月

                // 调整开始年月
                startMonth -= monthsToSubtract;
                while (startMonth < 1) {
                    startMonth += 12;
                    startYear--;
                }

                // 重新计算结束年月
                endYear = startYear + 1;
                if (startMonth + 11 > 12) {
                    endMonth = (startMonth + 11) % 12;
                    if (endMonth === 0) {
                        endMonth = 12;
                        endYear--;
                    }
                } else {
                    endMonth = startMonth + 11;
                }
            } else {
                // 如果没有超过当前年月，则endMonth不需要调整（但我们在前面已经计算过了）
                endMonth = (startMonth + 11) % 12 === 0 ? 12 : startMonth + 11;
            }
            if (endMonth > 12) endMonth = endMonth - 12;
            this.jiaDate = `${startYear}.${startMonth
                .toString()
                .padStart(2, "0")}-${endYear}.${endMonth
                .toString()
                .padStart(2, "0")}`;

            this.beginDate = `${startYear}${startMonth
                .toString()
                .padStart(2, "0")}`;
            this.overDate = `${endYear}${endMonth.toString().padStart(2, "0")}`;
        },

        async Sm2service_set_report() {
            if (!this.userInfo) {
                this.$confirm("该功能需要登录后使用", "提示", {
                    confirmButtonText: "去登录",
                    cancelButtonText: "再看看",
                })
                    .then(() => {
                        this.$router.push({
                            path: "/login",
                            query: {
                                url: "/tools/taxcount",
                            },
                        });
                    })
                    .catch(() => {});
                return;
            }
            if (this.userInfo.chashuibao_num == 0) {
                // this.$alert("暂无使用次数", "提示", {
                //     confirmButtonText: "确定",
                // });
                this.$confirm("暂无使用次数", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "购买额外次数",
                    distinguishCancelAndClose: true,
                    type: "warning",
                })
                    .then(() => {})
                    .catch((action) => {
                        if (action === "cancel") {
                            this.set_payVipShow({ show: true, index: 3 });
                        }
                    });
                return;
            }
            if (!this.form.companyName) {
                this.$alert("请输入企业名称", "提示", {
                    confirmButtonText: "确定",
                });
                return;
            }
            if (!this.jiaDate) {
                this.$alert("请选择申报时间", "提示", {
                    confirmButtonText: "确定",
                });
                return;
            }

            const res = await Sm2service_set_report({
                companyName: this.form.companyName,
                taxpayerId: this.form.taxpayerld,
                isAnonymity: this.form.isAnonymity,
                beginDate: this.beginDate,
                overDate: this.overDate,
            });
            if (res.code == 0) {
                localStorage.setItem("FXJC_CSB_orderNo", res.data.orderNo);
                window.open(res.data.initialUrl, "_blank");
            } else {
                this.$alert(res.message, "提示", {
                    confirmButtonText: "确定",
                });
            }
        },

        async querySearchAsync(queryString, cb) {
            if (!queryString || queryString.length < 5) {
                cb([]);
            } else {
                const res = await Sm2service_getbusinessfuzzy({
                    keyword: queryString,
                });
                if (res.code == 200) {
                    cb(res.data.data.splice(0, 5));
                }
            }
        },

        handleSelect(item) {
            console.log(item);
            this.form.companyName = item.companyName;
            this.form.taxpayerld = item.creditNo;
        },

        async gomyreport() {
            const res = await Sm2service_get_data({});
            if (res.code == 1 && res.data.length > 0) {
                this.$router.push({
                    path: "/riskdetection/myreport",
                });
            } else {
                this.$alert("暂无报告", "提示", {
                    confirmButtonText: "去检测",
                    showCancelButton: true,
                });
            }
        },

        gpylbg() {
            window.open(
                "https://xzcs-video.oss-cn-beijing.aliyuncs.com/pc/%E8%B4%A2%E7%A8%8E%E7%A5%A8%E7%BB%BC%E5%90%88%E6%A3%80%E6%B5%8B%E6%8A%A5%E5%91%8A.pdf",
                "_blank"
            );
        },
    },
};
</script>

<style lang="scss" scoped>
.event-main {
    width: 1200px;
    margin: 13px auto;
    background: linear-gradient(180deg, #c9e7ff 0%, #ffffff 12%);
    border-radius: 10px;
    padding: 47px 0 800px;
    position: relative;
    .Artboard2 {
        position: absolute;
        top: 9px;
        right: 8px;
    }
}
.risk-detection-title {
    font-weight: 700;
    font-size: 40px;
    color: #333333;
    text-align: center;
    span {
        color: #1c87f3;
    }
}

.risk-detection-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    font-size: 18px;
    color: #333333;
    margin-top: 40px;
    > div {
        height: 18px;
        width: 1px;
        background: #333333;
        margin: 0 16px;
    }
}

.form {
    width: 742px;
    margin: 68px auto 0;
}
.risk-detection-input {
    width: 100%;
    height: 60px;
    margin-bottom: 35px;
    display: block;
    font-size: 18px;
}

.input1 {
    &::v-deep .el-input__inner {
        font-size: 18px;
        height: 60px;
        border-radius: 10px;
        border-color: #000000;
        color: #333333;
        &:focus {
            border-color: #409eff;
        }
        &::placeholder {
            color: #777777;
        }
    }
}

.input2 {
    &::v-deep .el-input__inner {
        height: 60px;
        border-radius: 10px;
        border-color: #000000;
        color: #333333;
        &:focus {
            border-color: #409eff;
        }
        &::placeholder {
            color: #bababa;
        }
    }
}

.form-item {
    margin-bottom: 35px;
    .label {
        font-weight: 500;
        font-size: 24px;
        color: #333333;
        padding-right: 23px;
    }
    .radio {
        position: relative;
        top: -4px;
        &::v-deep .el-radio__label {
            font-size: 24px;
            color: #333333;
        }
    }
}

.submit {
    .button {
        width: 100%;
        height: 60px;
        border-radius: 10px;
        font-weight: 500;
        font-size: 24px;
    }
}
.selects {
    margin-top: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .select-item {
        display: block;
        width: 316px;
        height: 60px;
        line-height: 60px;
        text-align: center;
        background: #ffffff;
        border-radius: 10px;
        border: 1px solid #000000;
        font-weight: 400;
        font-size: 20px;
        color: #333333;
        cursor: pointer;
        span {
            padding-left: 155px;
        }
    }
}

.keyong-num {
    margin-top: 40px;
    font-weight: 400;
    font-size: 24px;
    color: #1c87f3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .zjcs {
        // color: #f56c6c;
        color: #333333;
        cursor: pointer;
    }
}

.sbsj-date-jia {
    position: relative;
    .date-text {
        line-height: 60px;
        color: #333333;
        font-size: 18px;
        position: absolute;
        left: 15px;
        top: 0;
    }
}

.sbsj-date {
    width: 100%;
    height: 60px;
    margin-bottom: 35px;
    display: block;
    font-size: 18px;
    &::v-deep .el-input__inner {
        height: 60px;
        border-radius: 10px;
        border-color: #000000;
        color: transparent;
        padding-left: 15px;
        &:focus {
            border-color: #409eff;
        }
        &::placeholder {
            color: #777777;
        }
    }
    &::v-deep .el-input__icon {
        display: none;
    }
}

.tips {
    padding-top: 30px;
    color: #f56c6c;
    font-size: 18px;
}
</style>
